package swa2012.telco.provider;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import swa2012.telco.broker.Broker;
import swa2012.telco.broker.BrokerCallback;
import swa2012.telco.broker.beans.*;
import swa2012.telco.provider.broker.BrokerCallbackImpl;

/**
 * @author kumar aberer
 * @date 10.06.2012
 */

public class TelcoProvider {

	private Broker broker;
	private BrokerCallbackImpl brokerCallback;
	private String identifier;
	private static MessageStorage msgs = new MessageStorage();
	private static ClientStorage clients = new ClientStorage();
	private Provider providerInstance = null;
	private ClientProvider clientProvider;
	private BrokerRegistrationStatus status = BrokerRegistrationStatus.REGISTRATION_ERROR;


	public TelcoProvider(String identifier) throws URISyntaxException{
		connectBroker();
		this.providerInstance = new Provider("12", new URI("http://student.swa.univie.ac.at:8012/SWA/BrokerCallback"));


		this.identifier = identifier;
		this.clientProvider = new ClientProviderImpl(this, msgs, clients);
		this.brokerCallback = BrokerCallbackImpl.getSingleInstance();
		this.brokerCallback.setClients(clients);
		this.brokerCallback.setMsgs(msgs);
		this.brokerCallback.setProvider(this);
		
		System.out.println("starting up telco provider..");

	}

	private void connectBroker() {
		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		factory.setServiceClass(Broker.class);
		factory.getInInterceptors().add(new LoggingInInterceptor());
		factory.getOutInterceptors().add(new LoggingOutInterceptor());
		factory.setAddress("https://swa.univie.ac.at/TelcoBroker/BrokerService");
		this.broker = (Broker) factory.create();
	}

	public void registerCallBack(String endpoint) throws URISyntaxException
	{
		//done manually
	}

	public Broker getBroker(){
		return broker;
	}

	public Provider getProvider(){
		return providerInstance;
	}

	public BrokerCallback getBrokerCallback()
	{
		return brokerCallback;
	}
	public ClientProvider getClientProvider() {
		return clientProvider;
	}

	@Override
	public void finalize(){
		try{
			broker.deregisterProvider(providerInstance);
		}
		catch(Exception e)
		{

		}
		finally{
		try {
			super.finalize();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}

}
